import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_util/common/extentions.dart';

import '../../../module/module_wallet/pages/wallet_mpc_securitymanager.dart';
import '../../../module/module_wallet/widgets/RotationImageWidget.dart';
import '../../bridge/native_channel_bridge.dart';
import '../../utils/util.dart';
import '../button/public_button.dart';
import 'package:aichat_flutter_wallet/module_common/utils/colors.dart';

class KaiBottomCloudDialog extends StatefulWidget {
  Function? Cancel;
  Function(String)? Confirm;

  KaiBottomCloudDialog({super.key, this.Cancel, this.Confirm});

  @override
  State<StatefulWidget> createState() {
    return _KaiBottomCloudDialogState();
  }
}

class _KaiBottomCloudDialogState extends State<KaiBottomCloudDialog> {
  MPCModel googleDriveInfo =
      MPCModel(type: MPCType.googleDrive, status: MPCStatus.normal);
  MPCModel iCloudInfo =
      MPCModel(type: MPCType.iCloud, status: MPCStatus.normal);

  Map<String, String> get stringMap {
    Map<String, String> result = {};
    return result;
  }

  bool isLoading = false;

  Widget typeImage(MPCType type) {
    String imgPath = '';
    switch (type) {
      case MPCType.server:
        imgPath = 'assets/images/wallet/upload_server.png';
        break;
      case MPCType.local:
        imgPath = 'assets/images/wallet/upload_local.png';
        break;
      case MPCType.googleDrive:
        imgPath = 'assets/images/wallet/upload_googledrive.png';
        break;
      case MPCType.iCloud:
        imgPath = 'assets/images/wallet/upload_icloud.png';
        break;
    }

    return Image.asset(imgPath, width: 20.w, height: 20.w);
  }

  //根据状态返回背景颜色
  Gradient? gradient(MPCStatus status) {
    switch (status) {
      case MPCStatus.success:
        return LinearGradient(
          colors: ["#FBFBFB".toColor(), '#F0FFFC'.toColor()], // 设置渐变的颜色列表
          begin: FractionalOffset.topLeft, // 设置渐变的起始位置
          end: FractionalOffset.bottomRight, // 设置渐变的结束位置
        );
      case MPCStatus.faild:
        return LinearGradient(
          colors: ["#FFFFFF".toColor(), '#FFF3F1'.toColor()], // 设置渐变的颜色列表
          begin: FractionalOffset.topLeft, // 设置渐变的起始位置
          end: FractionalOffset.bottomRight, // 设置渐变的结束位置
        );
      case MPCStatus.again:
        return LinearGradient(
          colors: ["#FFFFFF".toColor(), '#FFFAEA'.toColor()], // 设置渐变的颜色列表
          begin: FractionalOffset.topLeft, // 设置渐变的起始位置
          end: FractionalOffset.bottomRight, // 设置渐变的结束位置
        );
      case MPCStatus.normal:
        return null;
      case MPCStatus.ing:
        return null;
      case MPCStatus.disable:
        return null;
    }
  }

  //对应类型的title
  String typeTitle(MPCType type) {
    switch (type) {
      case MPCType.server:
        return 'Server';
      case MPCType.local:
        return 'Local';
      case MPCType.googleDrive:
        return 'Google Drive';
      case MPCType.iCloud:
        return 'iCloud';
    }
  }

  Widget row({required MPCModel model}) {
    return Container(
      height: 60.w,
      decoration: BoxDecoration(
        border: Border.all(color: "#E0E0E0".toColor()),
        borderRadius: BorderRadius.circular(10.w),
        gradient: gradient(model.status),
      ),
      child: Row(
        children: [
          Padding(
              padding: EdgeInsets.only(left: 15.w, right: 10.w),
              child: typeImage(model.type)),
          Expanded(
              child: Text(
            typeTitle(model.type),
            style: TextStyle(
                fontSize: 14.sp,
                color: '#333333'.toColor(),
                fontWeight: FontWeight.w500),
          )),
          rightWidget(model.type, model.status)
        ],
      ),
    );
  }

  //根据状态返回右边视图
  Widget rightWidget(MPCType type, MPCStatus status) {
    switch (status) {
      case MPCStatus.success:
        return Padding(
          padding: EdgeInsets.only(left: 10.w, right: 15.w),
          child: Image.asset(
            'assets/images/dapp/success.png',
            width: 20.w,
            height: 20.w,
          ),
        );
      case MPCStatus.faild:
        return Padding(
          padding: EdgeInsets.only(left: 10.w, right: 15.w),
          child: Image.asset(
            'assets/images/dapp/error.png',
            width: 20.w,
            height: 20.w,
          ),
        );
      case MPCStatus.again:
        return Padding(
          padding: EdgeInsets.only(left: 10.w, right: 15.w),
          child: GestureDetector(
            child: Container(
              padding: EdgeInsets.only(top: 7.w, bottom: 7.w),
              height: 30.w,
              width: 70.w,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(4.w),
                  color: '#FFA41A'.toColor()),
              child: Image.asset(
                'assets/images/wallet/refresh.png',
                fit: BoxFit.fitHeight,
              ),
            ),
            onTap: () {
              //上传、下载分片
              clickBtn(type);
            },
          ),
        );
      case MPCStatus.normal:
        return rightButton(type, status);
      case MPCStatus.ing:
        return rightButton(type, status);
      case MPCStatus.disable:
        return rightButton(type, status);
    }
  }

  //从google下载分片
  _googleDownLoad(bool isInit) {
    if (isLoading) {
      return;
    }
    isLoading = true;
    if (mounted)
      setState(() {
        googleDriveInfo.status = MPCStatus.ing;
      });
    try {
      WalletCheck.getGoogleKey().then((mpc) {
        if (mpc.$1.isEmpty) {
          googleDriveInfo.status = isInit ? MPCStatus.normal : MPCStatus.again;
        } else {
          googleDriveInfo.extension = mpc.$1;
          googleDriveInfo.status = MPCStatus.success;
        }
        Navigator.of(context).pop();
        if (widget.Confirm != null) {
          isLoading = false;
          widget.Confirm!(mpc.$1);
        }
        ;
        if (mounted) setState(() {});
      });
    } catch (e) {
      googleDriveInfo.status = isInit ? MPCStatus.normal : MPCStatus.again;
      Navigator.of(context).pop();
      if (widget.Confirm != null) {
        isLoading = false;
        widget.Confirm!('');
      }
      ;
      if (mounted) setState(() {});
    }
  }

  //iCloud下载，返回是否成功下载
  _iCloudDownLoad(bool isInit) async {
    if (isLoading) {
      return;
    }
    isLoading = true;
    if (mounted)
      setState(() {
        iCloudInfo.status = MPCStatus.ing;
      });
    try {
      WalletCheck.getIcloudKey().then((mpc) {
        if (mpc.$1.isEmpty) {
          iCloudInfo.status = isInit ? MPCStatus.normal : MPCStatus.again;
        } else {
          iCloudInfo.extension = mpc.$1;
          iCloudInfo.status = MPCStatus.success;
        }
        if (widget.Confirm != null) {
          isLoading = false;
          widget.Confirm!(mpc.$1);
        }
        ;
        if (mounted) setState(() {});
      });
    } catch (e) {
      iCloudInfo.status = isInit ? MPCStatus.normal : MPCStatus.again;
      if (widget.Confirm != null) {
        isLoading = false;
        widget.Confirm!('');
      }
      ;
      if (mounted) setState(() {});
    }
  }

  void clickBtn(MPCType type) {
    switch (type) {
      case MPCType.googleDrive:
        _googleDownLoad(false);
        break;
      case MPCType.iCloud:
        _iCloudDownLoad(false);
        break;
      default:
    }
  }

  Widget rotation() {
    return RotationImage(
        image: Image.asset('assets/images/wallet/downloading.png',
            width: 16, height: 16));
  }

  Widget rightButton(MPCType type, MPCStatus status) {
    bool isLoading = status == MPCStatus.ing;
    bool disabledStatus = isLoading || status == MPCStatus.disable;

    return Container(
        width: 70.w,
        margin: EdgeInsets.only(left: 10.w, right: 15.w),
        child: PublicButton(
          image: isLoading ? rotation() : null,
          radius: 4.w,
          margin: null,
          text: 'GET',
          height: 30.w,
          disabledStatus: disabledStatus,
          type: ButtonType.private,
          onClick: () {
            //上传、下载分片
            clickBtn(type);
          },
        ));
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      // margin: EdgeInsets.only(left: 32, right: 32, bottom: 40),
      padding: EdgeInsets.only(bottom: 40.w),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.w), // 设置圆角大小为 20
        color: Colors.white,
      ),
      width: double.infinity,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(
            height: 50.w,
            child: Stack(
              children: [
                Visibility(
                    visible: true,
                    child: IconButton(
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                        icon: const Icon(Icons.close))),
                Center(
                    child: Text(
                  '',
                  style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w500,
                      color: AppColors.c_333333),
                )),
              ],
            ),
          ),
          SizedBox(height: 30.w),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 20.w),
            child: row(model: googleDriveInfo),
          ),
          SizedBox(height: 15.w),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 20.w),
            child: Visibility(
                visible: Platform.isIOS &&
                    NativeChannelBridge
                            .instance.appCommMsg!.isAppleEnterprise ==
                        false,
                child: row(model: iCloudInfo)),
          ),
          SizedBox(height: 15.w),
        ],
      ),
    );
  }
}
